import Vue from 'vue'
import axios from 'axios'
import Vuex from 'vuex'
import {Http,Http2} from './help/axios.js';
import {app} from './help/app.js';
import VueAxios from 'vue-axios'
import App from './App'
import router from './router'
import $ from 'zepto'
import Interactive from './help/interactive.js'
import mui from './assets/mui/js/mui.js'
import './assets/mui/js/mui.picker.min.js'
import './assets/mui/css/mui.css'
import './assets/mui/css/mui.picker.all.css'
import 'vue2-toast/lib/toast.css';
import Toast from 'vue2-toast';
Vue.prototype.mui = mui
Vue.prototype.Http = Http;
Vue.prototype.Http2 = Http2;
Vue.prototype.interactive = Interactive;
Vue.prototype.app = app;
Vue.use(Vuex, VueAxios,axios)
Vue.use(Toast, {
  duration: 1500,
  wordWrap: true,
})
Vue.filter('splidate', function(dataStr) {
    if(!dataStr){
      return '';
    }
    return dataStr.match(/\d{4}-\d{2}-\d{2} \d{2}\:\d{2}:\d{2}/) ? dataStr.split(' ')[0] : dataStr;
})
Vue.filter('imgpre', function(dataStr) {
      return 'https://a.youzhijungroup.com/yzj/image/download/'+dataStr;
  })
Vue.filter('week', function(dataStr) {
    let str =  dataStr.replace(/-/g,'/');
    let day = new Date(str).getDay();
    return ["日", "一", "二", "三", "四", "五", "六"][day];
  })
Vue.filter('today', function(datestr) {
    let str =  datestr.replace(/-/g,'/');
    const mistiming = Math.round((new Date().getTime() - new Date(str).getTime()) / 1000)
    const tags = [ '天', '小时', '分钟', '秒']
    const times = [ 86400, 3600, 60, 1]
    for (let i = 0; i < times.length; i++) {
        const inm = Math.floor(mistiming / times[i])
        if (tags[i] === '天') {
            switch (inm) {
                case 0:
                    return '今天'
                    break
                case 1:
                    return '1天前'
                    break
                case 2:
                    return '2天前'
                    break
                default:
                    //return inm + tags[i] + '前'
                    return '3天前'
                    break;
            }
        }
        if (inm !== 0) {
            return inm + tags[i] + '前'
        }
      }
})
// 视图切换动画逻辑
const store = new Vuex.Store({
  state:{
    user:{},
    hasNew:false
  },
  actions:{
    SETUSER(ctx,user){
      ctx.commit('SETUSER',user)
    },
    SETNEWS(ctx,bool){
      ctx.commit('SETNEWS',bool)
    }
  },
  mutations:{
    SETUSER(state,user){
      state.user = user;
    },
    SETNEWS(state,bool){
      state.hasNew = bool;
    }
  }
})
let minicode = Http.getUrlParam('code');
router.beforeEach((to, from, next) => {
  let expire = localStorage.getItem('expire');
  if(expire && (new Date().getTime())>expire){
    localStorage.clear();
  }


  let uuid = localStorage.getItem("uid");
  let user = localStorage.getItem('user');
  if(to.query.shareId && !uuid){
    localStorage.setItem('shareId',to.query.shareId);
  }
  let city = Http.getUrlParam('minicity');
  if(city && !store.state.locate){
    store.state.locate = decodeURIComponent(city);
  }

  if (uuid && user) {
      next()
  } else {
      if(minicode){
        Http.post('/yzj/login/wechat/miniprogram', {
          code : minicode
        })
        .then((res) => {
          localStorage.removeItem("Authorization");
          localStorage.setItem("Authorization", `Bearer ${res.token}`);
          Http.get("/yzj/current-customer", null).then(user => {
            store.commit('SETUSER', user);
            localStorage.setItem("uid", user.id);
            localStorage.setItem("user",JSON.stringify(user));
            localStorage.setItem("expire", (new Date().getTime()+8.64*1e8));
            let shareId = localStorage.getItem('shareId');
            if(shareId){
              Http.jsonpost("/yzj/invitation", JSON.stringify({
                inviteeId: user.id,
                inviterId: shareId,
              })).then(res => {
                localStorage.removeItem('shareId');
              });
            }
            next();
          },(err)=>{
            minicode = null;
            next({ path: '/index' })
          });
        },(err) => {
          minicode = null;
          next({ path: '/index' })
        })
      }else if (to.path.match(/\/index|login|loginpass|bindphone|uagree|hotjobs|gangwei|searchresult|choosecity|infos|infodetail/) || to.path=='/') {
        next()
      } else {
        if(!!Http.getUrlParam('isSP')){//如果是在小程序里,跳转到登录页面
          wx.miniProgram.navigateTo({
            url: '../login/index'
          })
        }else{
          next({ path: '/login' })
        }
      }
  }
})

let api
// url：47.100.185.138   Youzhijun2019
//  port：51234
//  user：root
//  ^Pro_youzhijun2020^
api = location.protocol + '//' + location.host
axios.defaults.baseURL = api

new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App)
})
